﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Web;

namespace Toolkit.Web.Infastructure
{
    [DataContract]
    public abstract class ViewComponentBase : IViewComponent
    {
        protected ViewComponentBase(IViewComponentWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            Writer = writer;
            HtmlAttributes = new Dictionary<string, object>();
            SetIdentifier();
        }

        protected ViewComponentHtmlBuilderBase HtmlBuilder
        {
            get;
            set;
        }

        public IViewComponentWriter Writer
        {
            get;
            private set;
        }

        public IDictionary<string, object> HtmlAttributes
        {
            get;
            private set;
        }

        [DataMember]
        public string Identifier
        {
            get;
            set;
        }

        public virtual void Render()
        {
            WriteHtml(Writer);
        }

        public override string ToString()
        {
            using (StringWriter output = new StringWriter())
            {
                WriteHtml(new ViewComponentWriter(output));
                return output.ToString();
            }
        }

        public virtual void WriteHtml(IViewComponentWriter writer)
        {
            IHtmlNode htmlNode = HtmlBuilder.Html();
            if (htmlNode.GetType() == typeof(HtmlNode))
            {
                HtmlBuilder.ApplyComponentIdentifierAttribute(htmlNode);
            }
            htmlNode.WriteTo(writer);
        }

        private void SetIdentifier()
        {
            if (HttpContext.Current.Items["LastViewComponentIdentifier"] == null)
            {
                HttpContext.Current.Items["LastViewComponentIdentifier"] = 0;
            }

            int lastID = int.Parse(HttpContext.Current.Items["LastViewComponentIdentifier"].ToString());

            Identifier = (lastID + 1).ToString();

            HttpContext.Current.Items["LastViewComponentIdentifier"] = Identifier;
        }
    }
}
